package com.lemonfish.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Masics 张超
 * @date 2020/2/4 11:52
 */
@Configuration
public class MyDruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    //后台监控 相当于web.xml  ServletRegistrationBean
    //因为SpringBoot 内置servlet容器，所有没有web.xml ,想使用web.xml 就要使用 ServletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        //配置后台 {管理员} 帐号密码
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "123456");
        //增加配置
        //允许可以访问
        initParameters.put("allow", "");
        //禁止谁能访问
        //initParameters.put("kuang", "ip地址");
        bean.setInitParameters(initParameters);

        return bean;
    }

    // filter
    @Bean
    public FilterRegistrationBean filterRegistration() {
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());
        Map<String, String> initParameters = new HashMap<>();

        // 这些东西不进行统计
        initParameters.put("exclusions", "*.js,*.css,/druid/*");

        return bean;
    }
}
